TOP ?= test
WORK_DIR  = $(shell pwd)
BUILD_DIR = $(WORK_DIR)/build
CFLAGS += -CFLAGS -I$(WORK_DIR)/csrc/inc
LDFLAGS += -LDFLAGS -lreadline

CSRC += $(WORK_DIR)/csrc/$(TOP).cpp
CSRC += $(WORK_DIR)/csrc/src/*.cpp
VSRC += $(WORK_DIR)/vsrc/*/*.sv
VSRC += $(WORK_DIR)/vsrc/mcore/*/*.sv

BIN_DIR = $(BUILD_DIR)/$(TOP)

VFLAGS += --unroll-count 512
VFLAGS += -Wall  --sv
VFLAGS += --top $(TOP)
VFLAGS += -Wno-DECLFILENAME
VFLAGS += --trace-fst --trace-structs
VFLAGS += -Mdir $(BIN_DIR)
VFLAGS += -I$(WORK_DIR)/vsrc/mcore

BIN = $(BIN_DIR)/V$(TOP)

clean:
	@rm -r $(BUILD_DIR)

all: $(VSRC)
	@echo "Generating Simulator Model"
	@mkdir -p $(BUILD_DIR)
	@verilator --cc $(VSRC) $(CSRC) $(CFLAGS) $(LDFLAGS) $(VFLAGS) --exe -j 14 $(VARGS)

lint:
	verilator --lint-only $(VSRC) $(VFLAGS)

$(BIN): $(CSRC) all
	@echo "Compiling Simulator Model"
	@make -C $(BUILD_DIR)/$(TOP) -s -f V$(TOP).mk -j 14

run: $(BIN)
	$(BIN) $(ARGS) $(IMG)

perf: all
	@make -C $(BUILD_DIR)/$(TOP) -s -f V$(TOP).mk
	sudo perf record -o ./log/perf.data $(BIN) $(ARGS) $(IMG)
	sudo chmod +rw ./log/perf.data
	@perf report -i ./log/perf.data > ./log/perf.txt

TEST_DIR = ./bin
IMGS = $(basename $(notdir $(shell find $(TEST_DIR)/. -name "*.bin")))

$(IMGS): %: Makefile.%
COLOR_RED   = \033[1;31m
COLOR_GREEN = \033[1;32m
COLOR_NONE  = \033[0m
RESULT = .result
Makefile.%:
	@echo "$*:"
	@if $(BIN) $(ARGS) ./bin/$*.bin  ; then \
		printf "[%14s] $(COLOR_GREEN)PASS!$(COLOR_NONE)\n" $* >> $(RESULT); \
	else \
		printf "[%14s] $(COLOR_RED)FAIL!$(COLOR_NONE)\n" $* >> $(RESULT); \
	fi
	-@rm -f Makefile.$*

Test: $(BIN) Makefile.$(IMGS)
	cat $(RESULT)
	rm $(RESULT)